package cn.com.klun.step;

import cn.com.klun.tjy.base.IStep;
import cn.com.klun.tjy.cache.InitApplicationCache;
import cn.com.klun.tjy.dao.entity.TblAllStockInfo;
import cn.com.klun.tjy.dao.entity.TblTaskBasicConfig;
import cn.com.klun.tjy.dao.mapper.edit.TblAllStockInfoEditMapper;
import cn.com.klun.tjy.dao.mapper.ser.TblAllStockInfoSerMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
public class UpdateAllStockInfoTask implements IStep<TblAllStockInfo> {

    private Logger logger = LoggerFactory.getLogger(UpdateAllStockInfoTask.class);

    @Autowired
    private TblAllStockInfoSerMapper tblAllStockInfoSerMapper;
    @Autowired
    private TblAllStockInfoEditMapper tblAllStockInfoEditMapper;

    @Override
    public List queryTaskInfo(TblTaskBasicConfig config) {

        // 获取所有的股票信息
        String SHA = "C.2"; // 上证A
        String SZA = "C._A"; // 深证A
        logger.info("获取股票基本信息-定时执行任务，开始时间"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").format(new Date()));
        List<TblAllStockInfo> tblAllStockInfos = new ArrayList<>();
        if(spiderLogic(SHA, "sh", tblAllStockInfos)){
            logger.info("读取上证参数成功");
        }
        if(spiderLogic(SZA, "sz", tblAllStockInfos)){
            logger.info("读取深证参数成功");
        }
        return tblAllStockInfos;
    }

    @Override
    public void runTask(TblAllStockInfo tblAllStockInfo) {
        try{
            TblAllStockInfo allStock = new TblAllStockInfo();
            allStock.setStockCode(tblAllStockInfo.getStockCode());
            allStock.setEx(tblAllStockInfo.getEx().toUpperCase());
            TblAllStockInfo tblAllStockInfo1 = tblAllStockInfoSerMapper.queryObj(allStock);
            if(null == tblAllStockInfo1){
                tblAllStockInfoEditMapper.save(tblAllStockInfo);
                // 放入本地应用缓存当中 TODO ????
                InitApplicationCache.setAllStockInfo(tblAllStockInfo);
                logger.info("定时任务写入所有股票信息进入数据库成功{}",tblAllStockInfo.getStockCode());
            }
        }catch (Exception e){
            // TODO 放入异常信息库
            logger.info("写入数据库异常{}",e.getMessage());
        }
    }

    @Override
    public boolean editTaskInfo(List list) {
        return false;
    }


    /**
     * 获取网页数据并存储
     * @param zq
     * @param EX
     * @return
     */
    public boolean spiderLogic (String zq,String EX,List<TblAllStockInfo> list){
        int page = 1;
        int pageCount = 1;
        for (int i = 0; i <= pageCount; i++) {
            String url = "http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?type=CT&cmd="+zq+"&sty=FCOIATA&sortType=C&sortRule=-1&page="+page+"&pageSize=200&js=var%20quote_123={rank:[(x)],pages:(pc)}&token=7bc05d0d4c3c22ef9fca8c2a912d779c&jsName=quote_123&_g=0.9922115724443149";

            InputStream is = null;
            InputStreamReader isr = null;
            BufferedReader br = null;
            StringBuffer stockInfo = new StringBuffer();
            try {
                URL temp = new URL(url);
                URLConnection uc = temp.openConnection();
                uc.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0");
                is = temp.openStream();
                isr = new InputStreamReader(is);
                br = new BufferedReader(isr);
                String line;
                while((line = br.readLine()) != null){
                    stockInfo.append(line);
                }
            } catch (Exception e) {
                // TODO 处理异常 放入异常表
                logger.info("读取网页异常{}",e.getMessage());
            } finally {
                try {
                    is.close();
                    isr.close();
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            String resultInfo = stockInfo.toString();
            if(page == 1){
                pageCount = Integer.parseInt(resultInfo.substring(resultInfo.lastIndexOf("pages:")+6,resultInfo.lastIndexOf("}")));
            }
            resultInfo = resultInfo.substring(resultInfo.indexOf("[")+2,resultInfo.lastIndexOf("]")-1);
            String[] stocks = resultInfo.split("\",\"");
            int length = stocks.length;
            // "1,600398,海澜之家,11.44,0.85,8.03%,10.67,423854,475190304,10.59,10.58,11.65,10.52,-,-,-,-,-,-,-,-,-0.35%,3.31,0.94,15.34"
            for (int j = 0; j < length; j++) {
                String[] infos = stocks[j].split(",");
                TblAllStockInfo tblAllStockInfo = new TblAllStockInfo();
                tblAllStockInfo.setEx(EX);
                tblAllStockInfo.setStockCode(infos[1]);
                tblAllStockInfo.setName(infos[2]);
                list.add(tblAllStockInfo);
            }
        }
        return true;
    }
}
